from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from app import models
from django.utils import timezone
from django.core import serializers
import datetime


# Create your views here.
def admin_home(request):
    sql = 'select * from app_books'
    book_list = models.Books.objects.raw(sql, [])
    return render(request, 'adminHome.html', {'book_list': book_list})


# 用户首页
def user_home(request):
    sql = 'select * from app_books'
    book_lists = models.Books.objects.raw(sql, [])
    return render(request, 'userHome.html', {'book_lists': book_lists})


# 用户登录模块
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    # POST提交验证
    username = request.POST.get('username')
    password = request.POST.get('password')
    # 管理员
    if 'admin' in username:
        sql = 'select * from app_admin where admin_name = %s and password = %s'
        obj = models.Admin.objects.raw(sql, [username, password])
        flag = 1
    # 普通用户
    else:
        sql = 'select * from app_userinfo where username = %s and password = %s'
        obj = models.UserInfo.objects.raw(sql, [username, password])
        flag = 0

    if not obj:
        return JsonResponse({'status': False})

    request.session['username'] = username
    return JsonResponse({'status': True, 'flag': flag})


def logout(request):
    request.session.flush()
    return redirect('login')


# 注册界面
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    username = request.POST.get('username')
    password = request.POST.get('password')
    # obj = models.UserInfo.objects.filter(username=username, password=password).first()
    sql = 'select * from app_userinfo where username = %s'
    obj = models.UserInfo.objects.raw(sql, [username])

    if obj:
        return JsonResponse({'status': False})
    models.UserInfo.objects.create(
        username=username,
        password=password
    )
    return JsonResponse({'status': True})


# 补货操作
def add_num(request):
    bookId = request.POST.get('bookId')
    bookNum = request.POST.get('bookNum')
    sql = 'select * from app_books where id = %s'
    book = models.Books.objects.raw(sql, [bookId])
    if int(bookNum) < 0:
        return JsonResponse({'status': False})

    # 更新orm
    num = int(bookNum) + int(book[0].num)
    models.Books.objects.filter(id=bookId).update(num=num)
    return JsonResponse({'status': True})


# 删除书籍
def del_book(request):
    bookId = request.POST.get('bookId')
    models.Books.objects.filter(id=bookId).delete()
    return JsonResponse({})


# 管理员搜索书籍
def search_book(request):
    type = request.GET.get('type')
    title = request.GET.get('title')
    book_list = []

    if type == '0':
        book_list = models.Books.objects.filter(ISBN__icontains=title)
    elif type == '1':
        book_list = models.Books.objects.filter(book_name__icontains=title)
    elif type == '2':
        book_list = models.Books.objects.filter(author__icontains=title)
    elif type == '3':
        book_list = models.Books.objects.filter(press__icontains=title)

    return render(request, 'adminHome.html', {'book_list': book_list, 'flag': 1})


# 增加书籍
def add_book(request):
    ISBN = request.POST.get('ISBN')
    book_name = request.POST.get('bookName')
    author = request.POST.get('author')
    press = request.POST.get('press')
    price = request.POST.get('price')
    num = request.POST.get('num')
    models.Books.objects.create(
        ISBN=ISBN,
        book_name=book_name,
        author=author,
        price=price,
        press=press,
        num=num
    )
    return JsonResponse({})


# 用户搜索书籍
def user_search_book(request):
    user_type = request.GET.get('userType')
    user_title = request.GET.get('userTitle')
    book_lists = []

    if user_type == '0':
        book_lists = models.Books.objects.filter(ISBN__icontains=user_title)
    elif user_type == '1':
        book_lists = models.Books.objects.filter(book_name__icontains=user_title)
    elif user_type == '2':
        book_lists = models.Books.objects.filter(author__icontains=user_title)
    elif user_type == '3':
        book_lists = models.Books.objects.filter(press__icontains=user_title)

    return render(request, 'userHome.html', {'book_lists': book_lists, 'flag': 1})


# 借阅书籍
def borrow_book(request):
    bookid = request.POST.get('bookId')
    usersname = request.obj;

    timeNow = timezone.now()
    timeLater = timeNow + timezone.timedelta(days=30)

    book_obj = models.Books.objects.filter(id=bookid).first()
    # 触发器将对应书籍的num 减一
    user_obj = models.UserInfo.objects.filter(username=usersname).first()
    models.Records.objects.create(
        userId=user_obj,
        bookId=book_obj,
        due_date=timeLater
    )

    return JsonResponse({})


def admin_toAdmin(request):
    admin_list = models.Admin.objects.filter(manager=0)
    return render(request, 'adminToAdmin.html', {'admin_list': admin_list})


def del_admin(request):
    adminId = request.POST.get('adminId')
    models.Admin.objects.filter(id=adminId).delete()
    return JsonResponse({})


def add_admin(request):
    adminName = 'admin' + request.POST.get('adminName')

    if models.Admin.objects.filter(admin_name=adminName).first():
        return JsonResponse({'status': False})

    models.Admin.objects.create(
        admin_name=adminName,
        password=adminName
    )
    return JsonResponse({'status': True})


def manage_user(request):
    user_list = models.UserInfo.objects.all()
    return render(request, 'manageUser.html', {'user_list': user_list, 'status': 'user'})


def del_user(request):
    userId = request.POST.get('userId')
    userObj = models.UserInfo.objects.filter(id=userId).first()
    user_record = models.Records.objects.filter(userId=userObj)
    for item in user_record:
        if item.status == 0:
            return JsonResponse({'status': False})
    models.UserInfo.objects.filter(id=userId).delete()
    return JsonResponse({'status': True})


# 管理员管理借阅信息
def show_userRecord(request):
    userId = request.GET.get('userId')
    userObj = models.UserInfo.objects.filter(id=userId).first()
    record_list = models.Records.objects.filter(userId=userId)
    for record in record_list:
        record.borrowing_time = record.borrowing_time.strftime("%Y-%m-%d %H:%M:%S")
        record.due_date = record.due_date.strftime("%Y-%m-%d %H:%M:%S")
        if record.return_time:
            record.return_time = record.return_time.strftime("%Y-%m-%d %H:%M:%S")
    return render(request, 'manageUser.html', {'record_list': record_list, 'status': 'record', 'userObj': userObj})


# 管理员信息展示
def admin_detail(request):
    if request.method == 'GET':
        adminInfo = models.Admin.objects.filter(admin_name=request.obj).first()
        return render(request, 'adminDetail.html', {'adminInfo': adminInfo})

    sex = request.POST.get('sex')
    age = request.POST.get('age')
    if sex == '男':
        sex = 1
    else:
        sex = 2
    models.Admin.objects.filter(admin_name=request.obj).update(sex=sex, age=age)
    return JsonResponse({})


# 查询用户借的书
def my_borrow_book(request):
    userObj = models.UserInfo.objects.filter(username=request.obj).first()
    borrow_book_list = models.Records.objects.filter(userId=userObj)

    for obj in borrow_book_list:
        obj.borrowing_time = obj.borrowing_time.strftime("%Y-%m-%d %H:%M:%S")
        obj.due_date = obj.due_date.strftime("%Y-%m-%d %H:%M:%S")
        if obj.return_time:
            obj.return_time = obj.return_time.strftime("%Y-%m-%d %H:%M:%S")
    return render(request, 'myborrowbook.html', {'borrow_book_list': borrow_book_list})


# 归还书籍
def return_book(request):
    objId = request.POST.get('objId')
    timeNow = timezone.now()

    due_date = models.Records.objects.filter(id=objId).first().due_date

    if timeNow < due_date:
        models.Records.objects.filter(id=objId).update(return_time=timeNow, status=1, flag=0)
    else:
        models.Records.objects.filter(id=objId).update(return_time=timeNow, status=1, flag=1)

    # 还书触发器 完成对应书本num加一

    return JsonResponse({})


# 修改管理员密码
def edit_admin_password(request):
    password = request.POST.get('password')
    Pwd = request.POST.get('Pwd')
    if not models.Admin.objects.filter(admin_name=request.obj, password=password).first():
        return JsonResponse({'status': False, 'flag': 1})
    if password == Pwd:
        return JsonResponse({'status': False, 'flag': 0})
    models.Admin.objects.filter(admin_name=request.obj).update(password=Pwd)
    request.session.flush()
    return JsonResponse({'status': True, 'flag': 1})


# 展示归还书籍
def show_return_book(request):
    userObj = models.UserInfo.objects.filter(username=request.obj).first()
    return_book_list = models.Records.objects.filter(userId=userObj)

    for obj in return_book_list:
        obj.borrowing_time = obj.borrowing_time.strftime("%Y-%m-%d %H:%M:%S")
        obj.due_date = obj.due_date.strftime("%Y-%m-%d %H:%M:%S")
        if obj.return_time:
            obj.return_time = obj.return_time.strftime("%Y-%m-%d %H:%M:%S")
    return render(request, 'showreturnbook.html', {'return_book_list': return_book_list})


# 用户信息展示
def user_detail(request):
    if request.method == 'GET':
        userInfo = models.UserInfo.objects.filter(username=request.obj).first()
        return render(request, 'userDetail.html', {'userInfo': userInfo})
    sex = request.POST.get('sex')
    age = request.POST.get('age')
    if sex == '男':
        sex = 1
    else:
        sex = 2
    models.UserInfo.objects.filter(username=request.obj).update(sex=sex, age=age)
    return JsonResponse({})


# 修改用户密码
def edit_user_password(request):
    user_password = request.POST.get('userPassword')
    user_pwd = request.POST.get('userPwd')

    if not models.UserInfo.objects.filter(username=request.obj, password=user_password).first():
        return JsonResponse({'status': False, 'flag': 1})

    if user_password == user_pwd:
        return JsonResponse({'status': False, 'flag': 0})
    models.UserInfo.objects.filter(username=request.obj).update(password=user_pwd)
    request.session.flush()
    return JsonResponse({'status': True, 'flag': 1})
